package com.boy.service.weiXin;

import cn.hutool.json.JSONUtil;
import com.boy.base.Setting;
import com.boy.entity.Account;
import com.boy.service.WeatherService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author whd
 * @date 2024/08/16 11:29:01
 */
@Slf4j
@Service
public class WxServiceImpl implements WxService {
    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WeatherService weatherService;

    @Autowired
    private Setting setting;
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /*
     *
        💓可爱的：{{name.DATA}}
        * 📅今天是：{{today.DATA}}
        * 🌍城市：{{city.DATA}}
        *  ☁️今日天气：{{weather.DATA}}
        *  🌡️今日湿度：{{now_shidu.DATA}}
        * 🌕今日最低温度：{{min_temperature.DATA}}
        *  🌞今日最高温度：{{max_temperature.DATA}}
        * ❤️我们已经恋爱：{{love_date.DATA}}
        * 🎂距离你这个小笨蛋的生日还有：{{birthday.DATA}}
        *  🎉距离春节还有：{{diff_date1.DATA}}
        *  🌄日出时间：{{sunrise.DATA}}
        *  🌄日落时间：{{sunset.DATA}}
        * ☁️白天风向：{{windDirDay.DATA}}
        * ☁️空气指数：{{api.DATA}}
        * 🐝风力等级：{{windScaleDay.DATA}}
        *  💬{{note1.DATA}}{{note2.DATA}}{{note3.DATA}}{{note4.DATA}}{{note5.DATA}} ʕ•̫͡•ʔ•̫͡•ཻʕ•̫͡•ʔ•͓͡•ʔʕ•̫͡•ʔ•̫͡•ཻʕ•̫͡•ʔ•͓͡•ʔʕ•̫͡•ʔ
     *
     * */
    public void sendMessage(Account account) throws WxErrorException {
        String weather = weatherService.getWeather(account.getCityCode());
        Map result = JSONUtil.toBean(weather, Map.class);
        Map cityInfo = JSONUtil.toBean(result.get("cityInfo").toString(), Map.class);
        Map data = JSONUtil.toBean(result.get("data").toString(), Map.class);
        List<Map> forecast = JSONUtil.toList(data.get("forecast").toString(), Map.class);
        Map today = forecast.get(0);
        ArrayList<WxMpTemplateData> wxMpTemplateDataList = new ArrayList<>();
        wxMpTemplateDataList.add(new WxMpTemplateData("name", account.getNick()));
        wxMpTemplateDataList.add(new WxMpTemplateData("today", result.get("time").toString().split(" ")[0]));
        wxMpTemplateDataList.add(new WxMpTemplateData("city", cityInfo.get("city").toString()));
        wxMpTemplateDataList.add(new WxMpTemplateData("weather", today.get("type").toString()));
        wxMpTemplateDataList.add(new WxMpTemplateData("now_shidu", data.get("shidu").toString()));
        wxMpTemplateDataList.add(new WxMpTemplateData("now_wendu", data.get("wendu") + "°"));
        wxMpTemplateDataList.add(new WxMpTemplateData("max_temperature", today.get("high").toString().split(" ")[1] + "°"));
        wxMpTemplateDataList.add(new WxMpTemplateData("min_temperature", today.get("low").toString().split(" ")[1] + "°"));
        if (!Objects.equals(account.getCommemoration(), "no"))
            wxMpTemplateDataList.add(new WxMpTemplateData("love_date", getLoveDate(account.getCommemoration()) + "天"));
        wxMpTemplateDataList.add(new WxMpTemplateData("birthday", getBirthday(account.getBirthday()) + "天"));
        wxMpTemplateDataList.add(new WxMpTemplateData("diff_date1", getYear() + "天"));
        wxMpTemplateDataList.add(new WxMpTemplateData("sunrise", today.get("sunrise").toString()));
        wxMpTemplateDataList.add(new WxMpTemplateData("sunset", today.get("sunset").toString()));
        wxMpTemplateDataList.add(new WxMpTemplateData("windDirDay", today.get("fx").toString()));
        wxMpTemplateDataList.add(new WxMpTemplateData("windScaleDay", today.get("fl").toString()));
        wxMpTemplateDataList.add(new WxMpTemplateData("note1", today.get("notice").toString()));
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        wxMpTemplateMessage.setData(wxMpTemplateDataList);
        wxMpTemplateMessage.setToUser(account.getOpenid());
        wxMpTemplateMessage.setTemplateId(account.getTemplateId());
        wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
    }

    @Override
    public void setMenu() throws MalformedURLException, WxErrorException {
        WxMenu wxMenu = new WxMenu();
        WxMenuButton button31 = new WxMenuButton();
        button31.setType(WxConsts.MenuButtonType.VIEW);
        button31.setName("查看");
        button31.setUrl("http://47.94.221.242:8080");
        WxMenuButton button34 = new WxMenuButton();
        button34.setType(WxConsts.MenuButtonType.VIEW);
        button34.setName("获取用户信息");
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes != null) {
            HttpServletRequest request = servletRequestAttributes.getRequest();
            URL requestURL = new URL(request.getRequestURL().toString());
            String url = wxMpService.switchoverTo(setting.getWxAppId()).getOAuth2Service().buildAuthorizationUrl(
                    String.format("%s://%s/wx/redirect/%s/greet", requestURL.getProtocol(), requestURL.getHost(), setting.getWxAppId()),
                    WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
            button34.setUrl(url);
        }
        WxMenuButton button3 = new WxMenuButton();
        button3.setName("菜单");
        button3.getSubButtons().add(button31);
       // button3.getSubButtons().add(button34);
        wxMenu.getButtons().add(button3);
        wxMpService.switchover(setting.getWxAppId());
        String s = wxMpService.getMenuService().menuCreate(wxMenu);

    }

    private Long getBirthday(String data) {
        LocalDate birthday = LocalDate.parse(data, formatter);
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 获取今年的生日日期
        LocalDate thisYearBirthday = birthday.withYear(today.getYear());
        // 如果今年的生日已经过去了，计算明年的生日日期
        if (thisYearBirthday.isBefore(today) || thisYearBirthday.isEqual(today)) {
            thisYearBirthday = thisYearBirthday.plusYears(1);
        }
        // 计算天数差
        return ChronoUnit.DAYS.between(today, thisYearBirthday);
    }

    private Long getLoveDate(String data) {
        LocalDate givenDate = LocalDate.parse(data, formatter);
        // 获取当前日期
        LocalDate today = LocalDate.now();
        // 计算天数差
        return ChronoUnit.DAYS.between(givenDate, today);
    }

    private Long getYear() {
        String year2025 = "2025-02-07";
        String year2026 = "2026-02-06";
        String year2027 = "2027-01-29";
        LocalDate parse2025 = LocalDate.parse(year2025, formatter);
        LocalDate parse2026 = LocalDate.parse(year2026, formatter);
        LocalDate parse2027 = LocalDate.parse(year2027, formatter);
        // 获取当前日期
        LocalDate today = LocalDate.now();
        LocalDate springFestival;
        if (today.getYear() < parse2025.getYear()) {
            springFestival = LocalDate.of(2025, 2, 7);
        } else if (parse2025.getYear() == today.getYear()) {
            if (parse2025.getDayOfYear() >= today.getDayOfYear()) {
                springFestival = LocalDate.of(2025, 2, 7);
            } else {
                springFestival = LocalDate.of(2026, 2, 6);
            }
        } else if (parse2026.getYear() == today.getYear()) {
            if (parse2026.getDayOfYear() > today.getDayOfYear()) {
                springFestival = LocalDate.of(2026, 2, 6);
            } else {
                springFestival = LocalDate.of(2027, 1, 29);
            }
        } else {
            springFestival = LocalDate.of(2027, 1, 29);
        }

        // 计算天数差
        return ChronoUnit.DAYS.between(today, springFestival);
    }
}
